import TableContainer from "@/components/TableContainer"
import { PAGINATION_CONFIG } from "@/constants";
import { MeasureType } from "@/constants/enums/logisticsTemplate";
import {
  queryLogisticsTemplate, removeLogisticsTemplate, removeLogisticsTemplateArea,
} from "@/services/logisticsTemplate";
import { enum2options } from "@/utils/enum2options";
import { useRequest } from "ahooks";
import { Button, Col, Form, Popconfirm, Row, Select, Space, Table } from "antd"
import { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import { history } from '@umijs/max'
import TableActions from "@/components/TableActions";

const Device: React.FC = () => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<PaginationParams & {measureType?: MeasureType}>({
    pageNum: 1, pageSize: 10,
  })
  const templateList = useRequest(() => queryLogisticsTemplate(searchParams), {
    refreshDeps: [searchParams],
  })
  const delTemplateReq = useRequest(removeLogisticsTemplate, {manual: true})
  const delTemplateAreaReq = useRequest(removeLogisticsTemplateArea, {manual: true})

  const onFinish = (values: any) => {
    setSearchParams({
      ...searchParams,
      measureType: values.measureType,
    })
  }
  const delTemplate = (record: LogisticsTemplate) => {
    return delTemplateReq.runAsync({templateId: record.templateId!}).then(templateList.refresh)
  }
  const delTemplateArea = (record: LogisticsTemplate, subRecord: LogisticsTemplateArea) => {
    return delTemplateAreaReq.runAsync({templateId: record.templateId!, templateAreaId: subRecord.templateAreaId!}).then(templateList.refresh)
  }
  const addTemplate = () => {
    sessionStorage.setItem('__/mall/logistics/template/edit_title', '新建物流模板')
    history.push('/mall/logistics/template/edit')
  }
  const editTemplate = (record: LogisticsTemplate) => {
    sessionStorage.setItem('logisticsTemplateData', JSON.stringify(record))
    sessionStorage.setItem('__/mall/logistics/template/edit_title', '编辑物流模板')
    history.push('/mall/logistics/template/edit')
  }

  const columns: ColumnsType<LogisticsTemplate> = [
    {
      title: '模板名称',
      dataIndex: 'tplName',
    },
    {
      title: '计费方式',
      dataIndex: 'measureType',
      render: val => {
        switch (val) {
          case MeasureType.件数: return '件数'
          case MeasureType.重量: return '重量'
          case MeasureType.通用: return '通用'
          default: return '--'
        }
      }
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 220,
      render: (_, record) => {
        return (
          <TableActions>
            <a onClick={() => editTemplate(record)}>编辑</a>
            <Popconfirm
              title='确认删除该模板吗？'
              onConfirm={async () => delTemplate(record)}
            >
              <a>删除</a>
            </Popconfirm>
          </TableActions>
        )
      }
    },
  ]

  const expandedRowRender = (record: LogisticsTemplate) => {
    const columns: ColumnsType<LogisticsTemplateArea> = [
      {
        title: '可配送区域',
        dataIndex: 'area',
        render: area => {
          return JSON.parse(area)?.map((it: any) => it.label).join(',')
        }
      },
      {
        title: '首件(个)',
        dataIndex: 'startNum',
        width: 120,
      },
      {
        title: '运费(元)',
        dataIndex: 'startPrice',
        width: 120,
      },
      {
        title: '续件(个)',
        dataIndex: 'renewNum',
        width: 120,
      },
      {
        title: '续费(元)',
        dataIndex: 'renewPrice',
        width: 120,
      },
      {
        title: '操作',
        key: 'operations',
        width: 120,
        render: (_, subRecord) => {
          return <Space>
            <Popconfirm title='确认删除该配送区域吗？' onConfirm={async () => delTemplateArea(record, subRecord)}>
              <a>删除</a>
            </Popconfirm>
          </Space>
        }
      },
    ]

    return <Table<LogisticsTemplateArea> columns={columns} dataSource={record.area} pagination={false} size="small" />;
  }

  useEffect(() => {
    const refresh = () => {
      templateList.refresh()
    }
    window.addEventListener('refreshTemplateList', refresh)
    return () => {
      window.removeEventListener('refreshTemplateList', refresh)
    }
  }, [])
  
  return (
    <TableContainer>
      <TableContainer.Toolbar>
        <Button type='primary' onClick={addTemplate}>新建模板</Button>
      </TableContainer.Toolbar>
      <TableContainer.SearchContainer>
        <Form colon={false} name='searchStationListForm' form={searchForm} onFinish={onFinish}>
          <Row gutter={[20, 20]}>
            <Col span={6}>
              <Form.Item label='计费类型' name='measureType'>
                <Select placeholder='请选择' variant='borderless' options={enum2options(MeasureType)} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Space>
                <Button type='primary' htmlType='submit' loading={templateList.loading}>筛选</Button>
                <Button htmlType='reset'>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </TableContainer.SearchContainer>
      <Table<LogisticsTemplate>
        rowKey='templateId'
        loading={templateList.loading}
        dataSource={templateList.data?.data}
        columns={columns}
        scroll={{y: 700, x: 'max-content'}}
        pagination={{
          ...PAGINATION_CONFIG,
          current: searchParams.pageNum,
          pageSize: searchParams.pageSize,
          total: templateList.data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              pageNum: page === searchParams.pageNum ? 1 : page,
              pageSize,
            })
          },
        }}
        expandable={{
          expandedRowRender,
          rowExpandable: record => record.area?.length > 0,
        }}
      />
    </TableContainer>
  )
}

export default Device
